<template>
  <div class="app-container">
    <div class="filter-container filter-area">
      <!-- 为用户账号输入框添加标签说明 -->
      <label class="filter-item" style="margin-right: 10px;">用户账号:</label>
      <el-input
        v-model="listQuery.userNo"
        placeholder="用户账号"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <!-- 为用户姓名输入框添加标签说明 -->
      <label class="filter-item" style="margin-right: 10px;">用户姓名:</label>
      <el-input
        v-model="listQuery.userName__like"
        placeholder="用户姓名"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />

      <!-- 为状态筛选添加标签说明 -->
      <label class="filter-item" style="margin-right: 10px;">状态:</label>
      <el-select
        v-model="listQuery.sts"
        placeholder="状态"
        clearable
        style="width: 120px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option label="全部" value="" />
        <el-option v-for="item in statusOptions" :key="item.key" :label="item.stsDesc" :value="item.key" />
      </el-select>
    </div>

    <!-- 新增的操作按钮区 -->
    <div class="filter-container operation-area">
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 8px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加账号
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :height="tableHeight"
      :header-cell-style="{ background: '#fafafa' }"
    >
      <el-table-column label="ID" prop="id" align="center" width="100px">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户账号" min-width="60px">
        <template slot-scope="{row}">
          <span>{{ row.userNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户姓名" min-width="60px">
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="邮箱" min-width="80px">
        <template slot-scope="{row}">
          <span>{{ row.userEmail }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" width="160px" align="center">
        <template slot-scope="{row}">
          <el-tag v-for="role in row.roles" :key="role" :type="role | roleFilter">
            {{ role }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="150px">
        <template slot-scope="{row}">
          <span>{{ row.stsDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="230px"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.sts != '1'" size="mini" type="danger" @click="handleModifyStatus(row, '1')">
            禁用
          </el-button>
          <el-button v-else size="mini" type="success" @click="handleModifyStatus(row, '0')">
            启用
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row, $index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      class="pagination-container"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="账号" prop="userNo">
          <el-input v-model="temp.userNo" />
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="temp.userName" />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="temp.userEmail" />
        </el-form-item>
        <el-form-item v-if="dialogStatus === 'create'" label="密码" prop="userPwd">
          <el-input v-model="temp.userPwd" type="password" />
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="temp.roles" multiple placeholder="请选择角色">
            <el-option
              v-for="item in rolesOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="temp.sts" class="filter-item" placeholder="请选择">
            <el-option
              v-for="item in statusOptions"
              :key="item.key"
              :label="item.stsDesc"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, createAccount, updateAccount, deleteAccount, changeAccountStatus } from '@/api/account'
import waves from '@/directive/waves'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'

export default {
  name: 'AccountList',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        enabled: 'success',
        disabled: 'danger'
      }
      return statusMap[status]
    },
    roleFilter(role) {
      const roleMap = {
        admin: 'danger',
        editor: 'warning'
      }
      return roleMap[role] || 'info'
    }
  },
  data() {
    return {
      tableHeight: 'calc(100vh - 320px)',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        userName__like: '',
        userNo: '',
        sts: ''
      },
      temp: {
        id: undefined,
        userName: '',
        userEmail: '',
        userPwd: '',
        roles: [],
        sts: '0',
        stsDesc: '启用'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑账号',
        create: '创建账号'
      },
      rules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
      },
      statusOptions: [
        { key: '0', stsDesc: '启用' },
        { key: '1', stsDesc: '禁用' }
      ],
      rolesOptions: [
        { key: 'admin', display_name: '管理员' },
        { key: 'editor', display_name: '编辑者' }
      ],
      downloadLoading: false
    }
  },
  computed: {
    // 计算属性-动态计算状态下拉框的描述文本
    computedStsDesc: function() {
      const selectedOption = this.statusOptions.find(option => option.key === this.temp.sts)
      return selectedOption ? selectedOption.stsDesc : ''
    }
  },
  created() {
    this.getList()
    this.calculateTableHeight()
    window.addEventListener('resize', this.calculateTableHeight)
  },
  mounted() {
    // Watch for DOM changes that might affect filter area height
    this.observer = new MutationObserver(this.calculateTableHeight)
    this.observer.observe(document.querySelector('.filter-area'), {
      childList: true,
      subtree: true,
      attributes: true
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateTableHeight)
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        userName: '',
        userEmail: '',
        userPwd: '',
        roles: [],
        sts: '0'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const submitData = {
            ...this.temp,
            stsDesc: this.computedStsDesc // 动态计算的状态描述文本

          }

          createAccount(submitData).then((response) => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '保存成功',
              message: response.data.message,
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = {
            ...this.temp,
            stsDesc: this.computedStsDesc // 动态计算的状态描述文本
          }
          updateAccount(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('确认删除该账号?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAccount(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
        })
      })
    },
    handleModifyStatus(row, status) {
      const tempData = {
        id: row.id,
        sts: status,
        stsDesc: status === '0' ? '启用' : '禁用'
      }
      updateAccount(tempData).then(() => {
        this.getList()
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '状态修改成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    calculateTableHeight() {
      const filterHeight = document.querySelector('.filter-area')?.offsetHeight || 0
      const operationHeight = document.querySelector('.operation-area')?.offsetHeight || 0
      const paginationHeight = 60
      const padding = 40

      this.tableHeight = `calc(100vh - ${filterHeight + operationHeight + paginationHeight + padding}px)`
      this.$nextTick(() => {
        this.tableKey++ // Force table re-render
      })
    }
  }
}
</script>

<style scoped></style>
